
function [q,br,ef] = Q_cs(gamma,B,X,C,Z,xi,n,options,cmax,W)

N0 = n(1,1); N1 = n(1,2); N2 = n(1,3); N = N0 + N1 + N2;

% compute best responses to rivals' observed spending
parfor t = 1:N0
    tt = [t,N+t,2*N+t,2*N+N0+N2+t,3*N+N0+t];
    [br0(t,:),ef0(t,:)] = BRall(gamma,B,X(tt,:),C(tt,:),xi(tt,:),options,cmax,0); %#ok<*PFBNS>
end
parfor t = 1:N1
    tt = [N0+t,N+N0+t,1,2*N+N0+N2+N0+t,3*N+N0+N0+t];
    [br1(t,:),ef1(t,:)] = BRall(gamma,B,X(tt,:),C(tt,:),xi(tt,:),options,cmax,1);
end
parfor t = 1:N2
    tt = [N0+N1+t,N+N0+N1+t,2*N+N0+t,1,3*N+N0+N0+N1+t];
    [br2(t,:),ef2(t,:)] = BRall(gamma,B,X(tt,:),C(tt,:),xi(tt,:),options,cmax,2);
end

br = [br0;br1;br2];
ef = [ef0;ef1;ef2]; % Knitro exit flags

br = [br(1:N,1);br(1:N,2);br([1:N0,N0+N1+(1:N2)],3);br(1:N0+N1,4);br(1:N,5)]; % stack parties' best responses

g_hat = Z' * (C - br); % sample moment conditions

q = g_hat' * (W \ g_hat); % GMM objective



